package beans;

import entities.Checkout;
import entities.Utilisateur;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class CheckoutFacade extends AbstractFacade<Checkout> {

    @PersistenceContext(unitName = "ProjetAppliWebPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CheckoutFacade() {
        super(Checkout.class);
    }

    public Checkout create() {
        Checkout checkout = new Checkout();
        create(checkout);
        return checkout;
    }

    public Checkout getLast(Utilisateur u) {
        Query query = em.createQuery("SELECT c FROM Utilisateur u, IN(u.commandes) c WHERE u.id = :id AND c.valid = FALSE");
        query.setParameter("id", u.getId());

        try {
            return (Checkout) query.getSingleResult();
        } catch(NoResultException e) {
            return null;
        }
    }
}
